import axios from 'axios'

let defaultConfig = {
    timeout: 3000,
}
let instance = axios

class Axios {
    constructor(props) {
        if (props && typeof props == 'object') {
            instance = axios.create(props)
        } else {
            instance = axios.create(defaultConfig);
        }

        //拦截
        instance.interceptors.request.use((config) => {
            return config;
        }, (error) => {
            console.log(error)
            return Promise.reject(error);
        });

        //日志 响应结果
        instance.interceptors.response.use((response) => {
            return response.data;
        }, (error) => {
            console.log(error)
            return Promise.reject(error);
        })
    }

    send(params) {
        if (!params || typeof params != 'object') {
            throw new Error('params is undefined or not an object')
        }
        if (params.method == 'GET') {
            return get(params.url)
        } else if (params.method == 'POST') {
            return post(params.url, params)
        }
    }
}

async function get(url, callback) {
    try {
        let response = await instance.get(url)
        return response
    } catch (e) {
        console.log(e)
    }
}

async function post(url, params, callback) {
    try {
        let response = await instance.post(url)
        //eturn callback(response)
        return response
    } catch (e) {
        console.log(e)
    }
}

export default Instance = new Axios();